<template>
  <a-modal :title="formTile + '订阅消息模板'" :visible="true" width="60%" :footer="null" @cancel="reset">
    <a-card>
      <a-row type="flex" justify="start" align="top">
        <a-col :span="24">
          <a-form :form="form" @submit="handleSubmit" :labelCol="formItemLayout.labelCol" :wrapperCol="formItemLayout.wrapperCol">
            <a-form-item label="模板名称" :required="true">
              <a-input
                placeholder="请输入模板名称"
                v-decorator="[
                  `linkName`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入模板名称'
                      }
                    ]
                  }
                ]"
              />
            </a-form-item>
            <a-form-item label="适用小程序" :required="true">
              <a-select v-decorator="['brandId', { rules: [{ required: true, message: '请选择适用小程序!' }] }]" placeholder="请选择适用小程序">
                <a-select-option :value="item.weid" v-for="item in brands" :key="item.weid">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="模板id" :required="true">
              <a-input
                placeholder="请输入模板id"
                v-decorator="[
                  `template`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入模板id'
                      }
                    ]
                  }
                ]"
              />
            </a-form-item>
            <div v-for="(item, index) in fileds" :key="index">
              <a-form-item label="字段名称">
                <a-input
                  v-decorator="[
                    `names[${index}][lable]`,
                    {
                      initialValue: item['label'],
                      validateTrigger: ['change', 'blur'],
                      rules: [
                        {
                          required: true,
                          whitespace: true,
                          message: '请输入字段名称'
                        }
                      ]
                    }
                  ]"
                ></a-input>
              </a-form-item>
              <div class="template-name-icon">
                <a-form-item class="slef-item" label="字段变量">
                  <a-input
                    v-decorator="[
                      `names[${index}][val]`,
                      {
                        initialValue: item['val'],
                        validateTrigger: ['change', 'blur'],
                        rules: [
                          {
                            required: true,
                            whitespace: true,
                            message: '请输入字段变量'
                          }
                        ]
                      }
                    ]"
                  ></a-input>
                  <a-icon class="dynamic-delete-button mt-10" type="minus-circle-o" @click="() => remove(index)" />
                </a-form-item>
                
              </div>
            </div>
            <a-row>
              <a-col :span="16" :offset="8" >
                <a-button type="link" @click="add"> <a-icon type="plus" /> 添加消息模板字段 </a-button>
                <span type="link" @click="prevImage(insurl)" class="icon-info"
                  ><a-icon type="question-circle" style="margin-right:8px" />操作说明</span
                >
              </a-col>
            </a-row>
            <a-form-item label="启用状态" required>
              <a-radio-group v-decorator="['onlineState', { initialValue: 'Y' }]">
                <a-radio value="Y">
                  启用
                </a-radio>
                <a-radio value="N">
                  禁用
                </a-radio>
              </a-radio-group>
            </a-form-item>
            <a-row>
              <a-col :span="16" :offset="8" class="info-action">
                <a-button type="primary" @click="reset">返回</a-button>
                <a-button type="primary" html-type="submit" class="ml-20" :loading="loading">保存</a-button>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <a-modal v-model="visible" title="查看图片" @ok="visible = false" :footer="null" width="60%" :mask="true">
        <div class="previmg">
          <img :src="prevImageUrl" style="maxWidth:80%" />
        </div>
      </a-modal>
    </a-card>
  </a-modal>
</template>

<script>
let id = 0
import { brands } from '../util/brand'
import { createTemplate, templateDetail } from '@/api/micromall'
export default {
  props: {
    template: {
      type: Object,
      required: false,
      default: null
    }
  },
  // watch: {
  //   templateId: {
  //     immediate: true,
  //     deep: true,
  //     handler: function(n) {
  //       if (n != '' && n != -1) {
  //         this.getTemplateDetail(n)
  //       } else {
  //         this.form.resetFields()
  //         this.fileds = []
  //       }
  //     }
  //   }
  // },
  data() {
    return {
      insurl: 'https://picttype1.jnby.com/ins.PNG',
      brands,
      fileds: [],
      loading: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 6 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 12 },
          sm: { span: 12 }
        }
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 12, offset: 6 },
          sm: { span: 20, offset: 2 }
        }
      },
      prevImageUrl: '',
      visible: false,
      formTile: '新增'
    }
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'templateForm' })
  },
  created() {
    console.log(this.$props, 'props')
    const { template } = this.$props
    if (template) {
      this.getTemplateDetail(template)
      this.formTile = '编辑'
    }
  },
  methods: {
    async getTemplateDetail(template) {
      try {
        this.$nextTick(() => {
          const templateData = JSON.parse(template.templateData)
          console.log(templateData)
          let ary = []
          for (let key in templateData) {
            ary.push({ label: key, val: templateData[key] })
          }
          this.fileds = ary
          this.form.setFieldsValue({
            linkName: template.linkName,
            brandId: template.brandId,
            template: template.template,
            onlineState: template.onlineState
          })
        })
        // const res = await templateDetail({ id })
        // if (res.code == 200) {

        // } else {
        //   this.$message.error(res.msg)
        // }
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 预览操作说明
    prevImage(url) {
      this.prevImageUrl = url
      this.visible = true
    },
    // 重置表单
    reset() {
      this.form.resetFields()
      this.fileds = []
      this.$emit('close')
    },
    // 移除动态新增的元素
    remove(index) {
      let { fileds } = this
      fileds.splice(index, 1)
      this.fileds = fileds
    },
    // 新增元素
    add() {
      const obj = { lable: '', val: '' }
      let { fileds } = this
      fileds.push(obj)
      this.fileds = fileds
    },

    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log(values)
          this.submit(values)
        }
      })
    },
    // 提交
    submit(values) {
      this.loading = true
      console.log(values)
      const obj = {
        onlineState: values.onlineState,
        brandId: values.brandId,
        linkName: values.linkName,
        template: values.template,
        templateData: ''
      }
      console.log(this.template)
      // 编辑
      if (this.template) {
        obj.id = this.template.id
      }
      let templateData = {}
      if (values.names) {
        values.names.forEach(item => {
          templateData[item.lable] = item.val
        })
        obj.templateData = JSON.stringify(templateData)
      }
      console.log(obj)
      createTemplate(obj)
        .then(res => {
          this.loading = false
          if (res.code == 200) {
            let text = this.template ? '编辑成功' : '新增成功'
            this.$message.success(text)
            this.reset()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.msg)
        })
    }
  }
}
</script>
<style lang="less" scoped>
.dynamic-delete-button {
  cursor: pointer;
  position: absolute;
  right: -26px;
  top: 8px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}
.dynamic-delete-button:hover {
  color: #777;
}
.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
.self-item {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: flex-start;
  justify-content: flex-start;
}
.icon-info {
  color: orange;
  cursor: pointer;
}
.info-action {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 20px;
}
.ml-20 {
  margin-left: 20px;
}
.template-name-icon {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  position: relative;
}
.slef-item {
  width: 100%;
}
.mt-10{
  margin-top: -10px;
}
.previmg {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
